/* NOTICE
 
    Jim - the Java Image Manager, copyright (c) 2005 - 2007 Grant Gardner 
 
    Jim is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Jim is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
  
    In addition, as a special exception, you are permitted to link this code
    with the 3rd party libraries required to compile this file and to
    distribute a linked combination including them. You must obey the
    GNU General Public License in all respects for all of the code except for
    those 3rd party libraries that are licenced under terms incompatible with the
    GNU General Public License.  
 
 
 NOTICE */

package au.com.lastweekend.jim.util;

import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;

import au.com.lastweekend.jim.swing.SwingUtil;

/**
 * 
 * A worker thread for loading and displaying where both those activities are long-lived and the requested object can change
 * frequently.
 * 
 * Setting a new selected object does not interrupt the current loading, because I haven't found a way to abort an image from being
 * leaded through a media tracker, and interrupting simply causes us to spawn many image loading threads and eventually we run out
 * of memory.
 * 
 * @author grant@lastweekend.com.au
 * @version $Id: LoaderThread.java,v 1.2 2006/02/22 12:26:32 ggardner Exp $
 * @param <S>
 * @param <L>
 */
public class LoaderThread<S, L> extends Thread {

    private boolean finished = false;
    private final Loader<S, L> loader;
    private Iterator<? extends S> selectedIterator;
    private S first;

    private static final Logger LOG = Logger.getLogger(LoaderThread.class);

    public interface Loader<SS, LL> {

        LL load(SS selectedObject) throws InterruptedException;

        void display(SS selectedObject, LL loadedObject);

    }

    public LoaderThread(String name, Loader<S, L> loader) {

        super(name);
        this.loader = loader;
        List<S> emptyList = Collections.emptyList();
        selectedIterator = emptyList.iterator();
    }

    public void finish() {

        finished = true;
        interrupt();
    }

    @Override
    public void run() {

        LOG.debug("Starting " + this.getName());
        S displayed = null;
        while (!isFinished()) {

            S next;

            try {

                L loaded = null;

                next = waitForChange(displayed);

                if (next != null) {
                    loaded = loader.load(next);

                    if (!next.equals(getFirst())) {
                        // We don't want to display this
                        continue;
                    }

                }

                loader.display(next, loaded);

                displayed = next;

            } catch (InterruptedException e) {
                LOG.debug("Interrupted", e);
            }

        }
    }

    private synchronized S getFirst() {

        return first;
    }

    private synchronized S waitForChange(S displayed) throws InterruptedException {

        S next = null;
        while (!isFinished()) {

            next = getNextObject();

            if (next != null && !next.equals(displayed)) {
                // Load it!.
                break;
            } else if (displayed != null && displayed.equals(next)) {
                LOG.debug("Already displaying");
                // Already displaying this one, try the next one
                continue;
            }
            LOG.debug("Waiting");
            // We've run out of things to load.
            wait();
        }
        LOG.debug("Loading " + next);
        return next;

    }

    private synchronized S getNextObject() {

        if (selectedIterator.hasNext()) {
            return selectedIterator.next();
        }

        return null;
    }

    private boolean isFinished() {

        return finished;
    }

    public synchronized void setSelectedObject(S newSelection) {

        List<S> asList;
        if (newSelection == null) {
            asList = Collections.emptyList();
        } else {
            asList = Collections.singletonList(newSelection);
        }
        setSelected(asList);

    }

    /**
     * Load and display the first object. Until something changes, load the remaining objects one by one.
     * 
     * @param newSelection
     */
    public synchronized void setSelected(List<? extends S> newSelection) {

        if (newSelection == null) {
            newSelection = Collections.emptyList();
        }
        first = newSelection.size() > 0 ? newSelection.get(0) : null;
        selectedIterator = newSelection.iterator();

        notifyAll();

        SwingUtil.debugMemory(LOG);

    }
}
